const app = getApp();
Page({
  data: {
    Checkitem: '',
    CustomBar: app.globalData.CustomBar,
    selectCity: app.globalData.selectCity,
  },
  onLoad: function() {
    let that = this;
    // 如果获取位置成功才获取附近信息并设置天气
    if (app.globalData.location) {
      this.setData({
        weather: app.globalData.weather,
        location: app.globalData.location

      })
      this.getNearby();
      this.getNearTrafficSt();
    } else {
      wx.createSelectorQuery().select('.inputBox').boundingClientRect(function(rect) {
        that.setData({
          inputBoxHeight: rect.bottom - that.data.CustomBar + 10
        })
      }).exec();
    }
    this.historyFind();
    this.collect();
  },
  // 设置路线数组时检测是否存在于收藏当中
  setLineArr: function(LineArr, collect) {
    let this_ = this;
    collect = collect ? collect : wx.getStorageSync('collect-' + (this.data.selectCity == '珠海' ? 'zhuhai' : 'zhongshan'));
    console.log(collect)
    for (const i in LineArr) {
      for (const k in collect) {
        if (LineArr[i].Id == collect[k].Id) {
          console.log('有啊')
          LineArr[i].save = true;
          break;
        } else {
          LineArr[i].save = false;
        }
      }
    }
    console.log(LineArr)
    this_.setData({
      LineArr,
    })
  },
  // 获取附近交通状态
  getNearTrafficSt: function() {
    let that = this,
      globalData = app.globalData,
      url = "https://restapi.amap.com/v3/traffic/status/circle?";
    let dataArr = {
      key: app.globalData.mapKey,
      level: 4,
      extensions: "all",
      radius: 1000,
      location: globalData.location.longitude + "," + globalData.location.latitude,
    }
    app.reGetFn(url, dataArr, "direct").then(e => {
      let trafficinfo = e.data.trafficinfo;
      if (trafficinfo.evaluation.status == 1)
        trafficinfo.tImg = "/images/road/save.png";
      else if (trafficinfo.evaluation.status == 2)
        trafficinfo.tImg = "/images/road/anquanbiaozhi.png";
      else if (trafficinfo.evaluation.status == 3)
        trafficinfo.tImg = "/images/road/ting.png";
      else
        trafficinfo.tImg = "/images/road/honglvdeng.png";
      that.setData({
        trafficinfo,
      })
    })
  },
  // 获取附近车站
  getNearby: function() {
    let that = this,
      globalData = app.globalData;
    let url = "https://restapi.amap.com/v3/place/around?key=" + globalData.mapKey + "&location=" + globalData.location.longitude + "," + globalData.location.latitude + "&keywords=公交站&types=150700&radius=1000&offset=10&page=1&extensions=all";
    wx.request({
      url: url,
      method: 'get',
      success: function(res) {
        let pois = res.data.pois;
        let st = [];
        for (let i in pois) {
          st.push(pois[i].name.split("(公交站)")[0]);
        }
        that.setData({
          nearbyAddress: st
        })
        wx.createSelectorQuery().select('.inputBox').boundingClientRect(function(rect) {
          that.setData({
            inputBoxHeight: rect.bottom - that.data.CustomBar + 10
          })
        }).exec();
      },
    })
  },
  // 点击附近车站查询
  getStop: function(e) {
    app.showLoading("加载中...", true)
    let that = this,
      eBack = e,
      dataset = e.currentTarget.dataset;
    if (this.data.selectCity == '中山') {
      app.hideLoading()
      return;
    }
    let tagStop = encodeURIComponent(dataset.tagstop);
    let date = new Date();
    let time = Math.round(new Date().getTime() / 1000) + "000"
    let dataArr = {
      url: 'http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetLineListByStationName&key=' + tagStop + '&_=' + time,
      what: "Bus"
    }
    app.reGetFn(app.globalData.url, dataArr).then(e => {
      if (e.data == null || e.data == "")
        that.getStop(eBack)
      else {
        that.setLineArr(e.data.data)
        app.hideLoading()
      }
    })
  },
  // 更换城市 
  changeCity: function(e, city) {
    let this_ = this;
    this.setData({
      selectCity: city ? city : (this_.data.selectCity == '中山' ? '珠海' : '中山'),
      LineArr: [],
    })
    app.globalData.selectCity = city ? city : (app.globalData.selectCity == '中山' ? '珠海' : '中山');
  },
  // 点击键盘 or Search 搜索触发方法
  inputBox: function(e) {
    let this_ = this,
      value = e.detail.value.input ? e.detail.value.input : e.detail.value;
    if (value == "") return;
    if (this.data.inputValue == "" || this.data.inputValue == undefined) {
      this.setData({
        inputValue: value,
      })
      this.getCheckBus();
    }
  },
  // 查询路线方法
  getCheckBus: function() {
    let that = this;
    if (app.globalData.selectCity == '中山') {
      let data = {
          key: that.data.inputValue,
          type: 1,
          cityId: '021',
        },
        url = `https://zhongshan.yg84.com/api/basesearch/client/clientSearchList.action`;
      app.reGetFn(url, data, "direct").then(e => {
        let ygkj = e.data.split('YGKJ')[1],
          arr = [];
        ygkj = JSON.parse(ygkj).jsonr.data.lines
        that.historyFindAdd(that.data.selectCity, that.data.inputValue)
        that.setData({
          LineArr: ygkj,
          inputValue: "",
        })
      })
    } else if (app.globalData.selectCity == '珠海') {
      let date = new Date();
      let time = Math.round(new Date().getTime() / 1000) + "000"
      let dataArr = {
        url: 'http://www.zhbuswx.com/Handlers/BusQuery.ashx?handlerName=GetLineListByLineName&key=' + that.data.inputValue + '&_=' + time,
        what: "Bus"
      }
      app.reGetFn(app.globalData.url, dataArr).then(e => {
        if (e.data == null || e.data == "")
          that.getCheckBus();
        else {
          if (e.data.flag == 1004)
            that.setData({
              inputValue: "",
            })
          else {
            that.historyFindAdd(that.data.selectCity, that.data.inputValue)
            that.setData({
              inputValue: "",
              LineArr: e.data.data
            })
          }
        }
      })
    }
  },
  // 查询实时路线总方法
  lineChoose: function(e) {
    let that = this,
      item = '';
    for (let i in that.data.LineArr) {
      if (that.data.LineArr[i].Id == e.currentTarget.dataset.lineid) item = that.data.LineArr[i];
      if (that.data.LineArr[i].lineId == e.currentTarget.dataset.lineid) item = that.data.LineArr[i];
    }
    // 重复点击不会生效
    if ((that.data.Checkitem.Id == item.Id && app.globalData.selectCity == '珠海') || (that.data.Checkitem.lineId == item.lineId && app.globalData.selectCity == '中山')) {
      app.showToast('你点了同一路线同一方向', 'none', '', 2000, false)
      that.setData({
        nowCurrent: 1,
      })
      return;
    }
    app.globalData.BusCheckitem = item
    wx.navigateTo({
      url: '/pages/bus/busLine'
    })
  },
  // 历史查询添加
  historyFindAdd: function(city, busLine) {
    let this_ = this,
      historyFind = wx.getStorageSync('historyFind'),
      linshi = '';
    if (city == "" || busLine == "") return;
    let length = historyFind.length;
    if (length == 0) historyFind = [];
    for (const i in historyFind)
      if (historyFind[i].city == city && historyFind[i].busLine == busLine) {
        let linshi = historyFind[i];
        historyFind.splice(i, 1);
      }
    if (linshi == '') {
      if (length >= 5) historyFind.splice(4, 1)
      historyFind.splice(0, 0, {
        city: city,
        busLine: busLine,
      })
    } else {
      historyFind.splice(0, 0, linshi)
    }
    this.setData({
      historyFind,
    })
    wx.setStorageSync('historyFind', historyFind);
  },
  // 获取历史查询
  historyFind: function(e) {
    let this_ = this,
      historyFind = wx.getStorageSync('historyFind');
    this.setData({
      historyFind,
    })
    wx.setStorageSync('historyFind', historyFind);
  },
  // 点击历史查询的查询 
  historySelect: function(e) {
    let this_ = this,
      index = e.currentTarget.dataset.index,
      historyFind = this.data.historyFind,
      selectCity = this.data.selectCity;
    let tap = historyFind[index];
    this.changeCity('e', tap.city);
    this.setData({
      inputValue: tap.busLine,
    })
    this.getCheckBus();
  },
  // 收藏添加
  collectAdd: function(e) {
    let this_ = this,
      index = e.currentTarget.dataset.index,
      collect = wx.getStorageSync('collect-' + (this.data.selectCity == '珠海' ? 'zhuhai' : 'zhongshan')),
      LineArr = this.data.LineArr[index];
    let length = collect.length;
    if (length == 0) collect = [];
    for (const i in collect)
      if (collect[i].Id == LineArr.Id) {
        console.log('已有变删除');
        collect.splice(i, 1);
        wx.setStorageSync('collect-' + (this.data.selectCity == '珠海' ? 'zhuhai' : 'zhongshan'), collect);
        this.setLineArr(this.data.LineArr);
        return;
      }
    collect.splice(0, 0, LineArr)
    this.setData({
      collect,
    })
    wx.setStorageSync('collect-' + (this.data.selectCity == '珠海' ? 'zhuhai' : 'zhongshan'), collect);
    this.setLineArr(this.data.LineArr, collect);
  },
  // 获取收藏
  collect: function() {
    let this_ = this,
      collect = wx.getStorageSync('collect-' + (this.data.selectCity == '珠海' ? 'zhuhai' : 'zhongshan'));
    this.setLineArr(collect);
  }
})